package com.example.maze;

import java.util.HashSet;
import java.util.Set;

public class MazeGenerator {
//builds the maze
	public static Maze generate(int mazeSize, int percentageOfWalls){
		Position start = randomPosition(mazeSize);
		Position end = randomPosition(mazeSize);
		while(start.equals(end)){
			end = randomPosition(mazeSize);
		}
		Set<Position> walls = generateWalls(start, end, mazeSize, percentageOfWalls);
		return new Maze(start, end, walls);
	}
	//creates the walls
	private static Set<Position> generateWalls(Position start, Position end, int mazeSize, int percentageOfWalls) {
		//finds out how many walls are needed depending on what size and what percentage the user has selected
		int numberOfWalls = (int) (((float)(mazeSize*mazeSize)/100f)*percentageOfWalls);
		//creating an instance of the list of walls so its never empty
		Set<Position> walls = new HashSet<Position>();
		//creating the walls checking that they do not intersect the start and end positions
		for(int i =0; i < numberOfWalls; i++){
			Position wall = randomPosition(mazeSize);
			if(wall.equals(start)|| wall.equals(end) || walls.contains(wall)){
				i--;
			}else{
				walls.add(wall);
			}
		}
		//creating the size of the maze with walls surrounding x and y axis
		for(int y = -1; y <= mazeSize+1; y++){
			walls.add(new Position(-1, y));
		}
		for(int x = -1; x <= mazeSize+1; x++){
			walls.add(new Position(x, -1));
		}
		for(int x = -1; x <= mazeSize+1; x++){
			walls.add(new Position(x, mazeSize+1));
		}
		for(int y = -1; y <= mazeSize+1; y++){
			walls.add(new Position(mazeSize+1, y));
		}
		
		return walls;
	}
	//creating random coordinates for the start position
	private static Position randomPosition(int mazeSize){
		int randomXCoordinate = (int) (Math.random()* mazeSize);
		int randomYCoordinate = (int) (Math.random()* mazeSize);
		
		return new Position(randomXCoordinate, randomYCoordinate);
	}
	
	
}

